package com.skyolder.milkbee.web.rest;

import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.codahale.metrics.annotation.Timed;
import com.skyolder.milkbee.domain.Estate;
import com.skyolder.milkbee.repository.EstateRepository;
import com.skyolder.milkbee.web.rest.util.HeaderUtil;

/**
 * REST controller for managing Estate.
 */
@RestController
@RequestMapping("/api")
public class EstateResource {

    private final Logger log = LoggerFactory.getLogger(EstateResource.class);
        
    @Inject
    private EstateRepository estateRepository;

    /**
     * POST  /estates : Create a new estate.
     *
     * @param estate the estate to create
     * @return the ResponseEntity with status 201 (Created) and with body the new estate, or with status 400 (Bad Request) if the estate has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/estates")
    @Timed
    public ResponseEntity<Estate> createEstate(@RequestBody Estate estate) throws URISyntaxException {
        log.debug("REST request to save Estate : {}", estate);
        return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("estate", "forbidden", "can not create estate")).body(null);
        
        /*if (estate.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("estate", "idexists", "A new estate cannot already have an ID")).body(null);
        }
        Estate other=estateRepository.findByRank(estate.getRank());
        if(other!=null){
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("estate", "rank exists", "A new estate cannot already have an RANK")).body(null);
        }
        Estate result = estateRepository.save(estate);
        return ResponseEntity.created(new URI("/api/estates/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("estate", result.getId().toString()))
            .body(result);*/
    }

    /**
     * PUT  /estates : Updates an existing estate.
     *
     * @param estate the estate to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated estate,
     * or with status 400 (Bad Request) if the estate is not valid,
     * or with status 500 (Internal Server Error) if the estate couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/estates")
    @Timed
    public ResponseEntity<Estate> updateEstate(@RequestBody Estate estate) throws URISyntaxException {
        log.debug("REST request to update Estate : {}", estate);
        if (estate.getId() == null) {
            return createEstate(estate);
        }
        Estate result = estateRepository.save(estate);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("estate", estate.getId().toString()))
            .body(result);
    }

    /**
     * GET  /estates : get all the estates.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of estates in body
     */
    @GetMapping("/estates")
    @Timed
    public List<Estate> getAllEstates() {
        log.debug("REST request to get all Estates");
        List<Estate> estates = estateRepository.findAll();
        if(estates==null||estates.isEmpty()){
        	estates=Estate.initAll();
        	for(Estate e:estates){
        		estateRepository.save(e);
        	}
        }
        estates = estateRepository.findAll();
        return estates;
    }

    /**
     * GET  /estates/:id : get the "id" estate.
     *
     * @param id the id of the estate to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the estate, or with status 404 (Not Found)
     */
    @GetMapping("/estates/{id}")
    @Timed
    public ResponseEntity<Estate> getEstate(@PathVariable Long id) {
        log.debug("REST request to get Estate : {}", id);
        Estate estate = estateRepository.findOne(id);
        return Optional.ofNullable(estate)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /estates/:id : delete the "id" estate.
     *
     * @param id the id of the estate to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/estates/{id}")
    @Timed
    public ResponseEntity<Void> deleteEstate(@PathVariable Long id) {
        log.debug("REST request to delete Estate : {}", id);
        return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("estate", "forbidden", "can not delete estate")).body(null);
        
      /*  estateRepository.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("estate", id.toString())).build();
    */
    }

}
